"""


"""
from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from goods.models import SKUImage, SKU
from meiduo_admin.my_pagination import MyPageNumberPagination
from meiduo_admin.serializers import image_serializers
from utils.fdfs.MyFileStorage import MyStorage


class SKUImageView(ModelViewSet):
    pagination_class = MyPageNumberPagination
    serializer_class = image_serializers.SKUImageSerializer
    queryset = SKUImage.objects.all().order_by("id")

    def SKU_simple(self, request):

        skus_data = SKU.objects.all()

        serializer = image_serializers.SKUSimpleSerializer(instance=skus_data, many=True)

        return Response(serializer.data)

    def image_uploader(self, request):
        image = request.FILES["image"]

        mystorage = MyStorage()

        img_url = mystorage.save(None, content=image)

        if not img_url:
            return Response({
                "errmsg": "上传失败"
            }, status=status.HTTP_400_BAD_REQUEST)

        else:
            sku_id = request.data.get("sku")

            SKUImage.objects.create(sku_id=sku_id, image=img_url)

            return Response(status=status.HTTP_201_CREATED)

    def update(self, request, *args, **kwargs):

        image_obj = self.get_object()

        sku_id = request.data.get("sku")

        image = request.data.get("image")

        mystorage = MyStorage()

        img_url = mystorage.save(None, content=image)

        if not img_url:
            return Response({
                "errmsg": "上传失败"
            }, status=status.HTTP_400_BAD_REQUEST)

        else:
            image_obj.sku_id = sku_id
            image_obj.image = img_url
            image_obj.save()

            return Response(status=status.HTTP_201_CREATED)
